#include <jni.h>
#include <string>
#include <pthread.h>
#include "MyLog.h"
extern "C" {
void dynamicTest() {
    LOGE("dynamicTest");
}

int dynamicTest2(JNIEnv *env, jobject thiz, jint ji) {
    LOGE("dynamicTest2 ji = %d", ji);
}

}

//动态注册
JavaVM * _vm;
static const JNINativeMethod method[] = {
        {"dynamicJavaTest", "()V", (void*)dynamicTest},
        {"dynamicJavaTest2", "(I)I", (void*)dynamicTest2},
};
static const char* mClassName = "com/example/testjni/MainActivity";

jint JNI_OnLoad(JavaVM *vm, void *r) {
    LOGE("JNI_Onload 00000 ");
    _vm = vm;
    JNIEnv *env = nullptr;
    int a = vm->GetEnv((void**)&env, JNI_VERSION_1_6);
    if(a != JNI_OK) {
        return -1;
    }
    jclass jcls = env->FindClass(mClassName);
    env->RegisterNatives(jcls, method, sizeof(method)/ sizeof(JNINativeMethod));
    return JNI_VERSION_1_6;
}

struct Context{
    jobject instance;
};

void * threadTask(void * args) {
    //子线程不能使用主线程的env

    //下载完成
    //下载失败

    //native线程附加到java虚拟机
    JNIEnv *env;
    jint i = _vm->AttachCurrentThread(&env, 0);
    if(i != JNI_OK) {
        return 0;
    }
    Context *context = static_cast<Context *>(args);
    jclass jcls = env->GetObjectClass(context->instance);
    jmethodID updateUI = env->GetMethodID(jcls, "updateUI", "()V");
    env->CallVoidMethod(context->instance, updateUI);

    delete context;
    context = 0;
    env->DeleteGlobalRef(context->instance);
    _vm->DetachCurrentThread();//分离
    return 0;
}
extern "C"
JNIEXPORT void JNICALL
Java_com_example_testjni_MainActivity_testThread(JNIEnv *env, jobject thiz) {
    pthread_t pid;
    Context * context = new Context;
    context->instance = env->NewGlobalRef(thiz);
    pthread_create(&pid, 0, threadTask, context);
}


